<?php

class Admin_Controller {

  /**
   * @var User $user
   */
  protected $user;

  public function __construct(Request $request, Response $response) {
    if (isset($_COOKIE['_uid']) && isset($_COOKIE['_secret']) && $user = User::load($_COOKIE['_uid'])) {
      $this->user = $user;
      /**
       * @var User $user
       */
      if ($user->type != User::TYPE_ADMINISTRATOR) {
          setcookie("_uid", '', time(), '/admin/', ADMIN_HOST);
          $response->redirect('/session/login/');
      }
    } elseif ($request->uri() != '/admin/session/login/') {
      $response->redirect('/session/login/');
    }
  }
  public function index(Request $request, Response $response) {
    $class = 'Admin' . ucfirst($request->path(1)) . '_Controller';
    $file = ROOT . '/controller/admin/' . $class . '.php';
    if (!file_exists($file)) {
      $class = 'AdminCollege_Controller';
    }
    $file = ROOT . '/controller/admin/' . $class . '.php';
    include($file);
    $ctr = new $class($request, $response);
    $method = $request->path(2);
    if (!is_callable([$class, $method])) $method = 'index';
    $ctr->$method($request, $response);
  }
  protected function clearCookie() {
    setcookie("_uid", '', time(), '/', ADMIN_HOST);
    setcookie("_uid", '', time(), '/', '*.'.ADMIN_HOST);
    setcookie("_secret", '', time(), '/', ADMIN_HOST);
    setcookie("_secret", '', time(), '/', '*.'.ADMIN_HOST);
  }
}